import { defineStore } from "pinia"
import type { User } from "@/env"
import { cloneDeep } from 'lodash'
import { getToken } from "./global"
import { getUser, updateSetting } from "@/api/user"


/** 初始User内容 */
const initUser : User = {
	id: '0',
	name: '',
	img: '',
	info: {},
	setting: {
		page: {
			theme: uni.getStorageSync('theme') || 'light',
		},
		mylog: {
			tags: [],
			filters: [],
			filterIndex: -1,
			calendarTags: [],
		},
		map: {
			diyPoints: [
				// {
				//   lnglat: [103.00042, 29.983349],
				// },
				// {
				//   lnglat: [103.00042, 29.984349],
				// },
			],
		},
	},
	createtime: undefined,
	openidQ: undefined,
}

export const useUserStore = defineStore('user', () => {
	console.log('获取用户数据，重新执行UserStore')
	// 当前默认用户数据，这里下面用了toRefs，所以要在这里把全部属性定义好
	const user = reactive<User>(cloneDeep(initUser))

	/**
	 * 响应式的登录状态
	 */
	const isLogined = ref<boolean>(!!getToken())

	watch(isLogined, () => {
		if (isLogined.value) {
			getUser({ token: getToken()! }).then(res => {

				const userdata = cloneDeep(res)
				// 临时删掉东西
				const setting = res.setting
				// @ts-ignore 这里用deepMerge会有意想不到得bug，慎用
				delete userdata.setting
				Object.assign(user, userdata)
				Object.assign(user.setting.page, setting.page)
				Object.assign(user.setting.mylog, setting.mylog)
				Object.assign(user.setting.map, setting.map)
				// 获取到远端用户setting在注册监视，同步双端
				watch(user.setting, () => {
					const settingJson = JSON.stringify(user.setting)
					updateSetting({ settingJson }).then(count => {
						if (count) {
							console.log('🐤 setting 设置更改成功')
							localStorage.setItem('setting', settingJson)
						}
					})
				})
			})
		}
	}, { immediate: true })


	// 先去本地存储获取页面设置
	// const pageSetting = localStorage.getItem('pageSetting')
	// if (pageSetting) deepMerge(user.setting!, JSON.parse(pageSetting))

	const reset = () => {
		Object.assign(user, cloneDeep(initUser))
	}

	return {
		/** 是否登录 */
		isLogined,
		...toRefs(user),
		/** 手动重置 */
		reset
	}
})

export default useUserStore